﻿package 
{

	import flash.display.MovieClip;
	import connection.Connection;
	import flash.utils.Dictionary;
	import flash.events.MouseEvent;
	import connection.Packet;
	import entity.UserInfo;
	import HandlerEvent.PacketHandler;


	public class LoginForm extends MovieClip
	{

		private var conn:Connection;
		private var dict:Dictionary;
		private var loginForm:LoginForm;
		public var parentFrame;
		private var userInfo:UserInfo;

		public function LoginForm()
		{
			// constructor code
			txtPass.displayAsPassword = true;
			dict = new Dictionary();
		}

		public function doAction():void
		{
			btnLogin.addEventListener(MouseEvent.CLICK,doSendLogin);
			this.conn.addEventListener(PacketHandler.RECEIVE_NORMAL_ACTIVE_PACKET,doCommand);
		}

		public function setConnection(c:Connection):void
		{
			conn = c;
		}

		public function doCommand(event:PacketHandler):void
		{
			this[dict[conn.getReceivePacket().getCommandSenderID()]]();
		}

		public function doSendLogin(evnt:MouseEvent):void
		{
			if (txtName.text != "" && txtPass.text != "")
			{
				var userStr:String = txtName.text;
				var passStr:String = txtPass.text;
				var loginPacket:Packet = new Packet();
				loginPacket.setHeaderFlag(0);
				loginPacket.setCommandCode("LGI");
				loginPacket.setCommandType(0);
				var randomValue:int = Math.floor(Math.random() * 1000000000);
				loginPacket.setCommandSenderID(randomValue);
				loginPacket.setContent(JSON.stringify([userStr,passStr]));
				loginPacket.setHeaderDataLength(8+loginPacket.getContent().toString().length);
				loginPacket.printPacket();
				dict[loginPacket.getCommandSenderID()] = "doLogin";
				this.conn.sendPacket(loginPacket);
			}
			else
			{
				txtMessage.text = "Mời bạn nhập đầy đủ thông tin!";
			}

		}

		public function doLogin():void
		{
			if (conn.getReceivePacket().getCommandCode() == "LGI" && conn.getReceivePacket().getCommandType() == 0)
			{
				var okLogin:int = conn.getReceivePacket().getContent().indexOf("ok");
				if (okLogin != -1)
				{
					conn.removeEventListener(PacketHandler.RECEIVE_NORMAL_ACTIVE_PACKET,doCommand);
					this.parentFrame.gotoAndPlay(2);
				}
				var jsonPar = JSON.parse(conn.getReceivePacket().getContent());
				var error_code:int = jsonPar.error_code;
				if (error_code == 4)
				{
					txtMessage.text = "Tài khoản chưa tồn tại. Mời bạn đăng ký!";
				}
				else if (error_code == 5)
				{
					txtMessage.text = "Username hoặc password chưa đúng. Mời bạn nhập lại!";
				}
			}

		}
	}

}